<?php

namespace W3\Element;

use W3\Element;

/**
 * Radio 帮手类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Radio extends Group 
{
    /**
     * 选择值
     *
     * @access private
     * @var array
     */
    private $options = [];
	
    /**
     * 构造函数
     *
     * @access public
     * @param string $name 表单输入项名称
     * @param mixed $value 表单默认值
     * @param array $options 选择项
     * @return void
     */
    public function __construct($name = NULL, array $options = [], $checked = NULL)
    {
		$this->name = $name;
        foreach ($options as $value => $label) 
		{
			++self::$uniqueId;
			$id =  '__radio_' . self::$uniqueId;
		    $container = Div::make(null, 'custom-control custom-radio');
		    $label = Label::make($label, 'custom-control-label');
			
		    $radio = Input::make($this->name, $value)
			    ->id($id)
				->type('radio')
				->addClass('custom-control-input');

			$container->set($radio)->set($label->for($id));
			$this->options[$value] = $radio;
            $this->set($container);
        }
		
        /** 初始化表单值 */
        if (NULL !== $checked) {
            $this->value($checked);
        }
    }
	
    /**
     * setChecked
     *
     * Set form element as checked
     *
     * @param boolean  $checked   Value
     *
     * @return $this;
     */
    public function value($value) 
	{
		$this->value = $value;
		
        foreach ($this->options as $option) 
		{
            $option->removeAttribute('checked');
        }
		
		if(isset($this->options[$value])) {
			$this->value = $value;
		    $this->options[$value]->attribute('checked', 'true');
		}

        return $this;
    }
}